//------------------------------------------------------------------------------
// Copyright (c) 2012 Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------

package com.dhh.sky.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import com.dhh.sky.R;
import com.dhh.sky.activity.FileListActivity;
import com.dhh.sky.activity.MenuActivity;
import com.korovyansk.android.slideout.SlideoutActivity;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class FilePicker extends ListActivity {
    private Map<String,String> uploadFiles;
    private Map<String,String> uploadNames;
    private ActionBar actionBar;
	private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options;
	private LinearLayout upLst;
    
    private class FilePickerListAdapter extends BaseAdapter {
        private final LayoutInflater mInflater;
        private final ArrayList<File> mFiles;
        private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        public FilePickerListAdapter(Context context) {
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mFiles = new ArrayList<File>();
            uploadFiles = new HashMap<String,String>(); 
            uploadNames = new HashMap<String,String>(); 
        }

        public ArrayList<File> getFiles() {
            return mFiles;
        }

        @Override
        public int getCount() {
            return mFiles.size();
        }

        @Override
        public File getItem(int position) {
            return mFiles.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView != null ? convertView :
                                           mInflater.inflate(R.layout.file_list_select_item,
                                                             parent,
                                                             false);
            Button icon = (Button) v.findViewById(R.id.fli_icon);
            TextView name = (TextView) v.findViewById(R.id.fli_title);
            TextView date = (TextView) v.findViewById(R.id.fli_date);
            TextView size = (TextView) v.findViewById(R.id.fli_size);

            File file = getItem(position);
            name.setText(file.getName());
            Date mDate = new Date();
            mDate.setTime(file.lastModified());
            date.setText(format.format(mDate));
            if(file.isDirectory()){
            	icon.setBackgroundResource(R.drawable.ic_folder);
            	icon.setVisibility(View.VISIBLE);
            	v.findViewById(R.id.fli_select).setVisibility(View.GONE);
        		v.findViewById(R.id.fli_img).setVisibility(View.GONE);
            }else{
            	v.findViewById(R.id.fli_select).setVisibility(View.VISIBLE);
            	if(uploadFiles.get(file.getName())!=null)
            		v.findViewById(R.id.fli_select).setBackgroundResource(R.drawable.ic_selection_on);
            	else
            		v.findViewById(R.id.fli_select).setBackgroundResource(R.drawable.ic_selection_off);
            	
            	String ext = FileUtil.getFileExt(file.getName());
            	if(FileUtil.audioType.contains(ext)){
                	icon.setBackgroundResource(R.drawable.ic_audio);
            	}else if(FileUtil.vedioType.contains(ext)){
                	icon.setBackgroundResource(R.drawable.ic_vedio);
            	}else if(FileUtil.imgType.contains(ext)){
            		icon.setVisibility(View.GONE);
    				ImageView img = (ImageView) v.findViewById(R.id.fli_img);
    				imageLoader.displayImage("file:///"+file.getAbsolutePath(), img, options);
    				img.setVisibility(View.VISIBLE);   
                	v.findViewById(R.id.fli_select).setVisibility(View.VISIBLE);
            	}else if(FileUtil.docType.contains(ext)){
                	icon.setBackgroundResource(R.drawable.ic_doc);
            	}else if(FileUtil.excelType.contains(ext)){
                	icon.setBackgroundResource(R.drawable.ic_excel);
            	}else if(FileUtil.powPointType.contains(ext)){
                	icon.setBackgroundResource(R.drawable.ic_pps);
            	}else if(FileUtil.pdfType.contains(ext)){
                	icon.setBackgroundResource(R.drawable.ic_pdf);
            	}else if(FileUtil.zipType.contains(ext)){
                	icon.setBackgroundResource(R.drawable.ic_zip);
            	}else{
            		icon.setBackgroundResource(R.drawable.ic_file_w);
            	}
            }
            
            String sVal = "";
            if(!file.isDirectory()){
            	sVal = "1 KB";
                if(file.length()/1024 > 1){
                	sVal = (file.length()/1024) + " KB";
                }
                
            }
            size.setText(sVal);
           
            
            return v;
        }
    }

    public static final int PICK_FILE_REQUEST = 0;
    public static final String EXTRA_FILE_PATH = "filePath";

    private File mCurrentFolder;
    private Stack<File> mPrevFolders;
    private FilePickerListAdapter mAdapter;
    private String ROOT_NAME;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.file_picker);
		upLst = (LinearLayout) findViewById(R.id.fl_up_lst);
        mPrevFolders = new Stack<File>();
		imageLoader.init(ImageLoaderConfiguration.createDefault(this));
		options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.stub_image)
					.showImageForEmptyUrl(R.drawable.image_for_empty_url)
					.cacheInMemory()
					.cacheOnDisc()
					.build();

        ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setDivider( null );
		lv.setDividerHeight(0); 
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                File file = (File) parent.getItemAtPosition(position);

                if (file.isDirectory()) {
                    mPrevFolders.push(mCurrentFolder);
                    loadFolder(file);
                } else {
                	String name = file.getName();
                	if(uploadFiles.get(name)!=null){
                		uploadFiles.remove(name);
                		uploadNames.remove(name);
                		view.findViewById(R.id.fli_select).setBackgroundResource(R.drawable.ic_selection_off);
                		if(uploadFiles.isEmpty()){
                			actionBar.removeAllActions();
                			actionBar.addAction(new AllAction());
                    		actionBar.addAction(new InfoAction());
                		}else{
                			actionBar.removeAllActions();
                			actionBar.addAction(new AllAction());
                			actionBar.addAction(new UploadAction());
                    		actionBar.addAction(new InfoAction());
                		}
                	}else{
                		if(uploadFiles.isEmpty()){
                			actionBar.addAction(new UploadAction(),1);
                		}
                		uploadFiles.put(name, file.getAbsolutePath());
                		uploadNames.put(name, name);
                		view.findViewById(R.id.fli_select).setBackgroundResource(R.drawable.ic_selection_on);
                	}
                }
            }
        });

        mAdapter = new FilePickerListAdapter(FilePicker.this);
        
        setListAdapter(mAdapter);
    }
    
    private class HomeAction implements Action {
	    @Override
	    public int getDrawable() {
	        return R.drawable.ic_home_arrow;
	    }

	    @Override
	    public void performAction(View view) {	    	
	    	int width = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());
			SlideoutActivity.prepare(FilePicker.this, R.id.inner_content, width);
			startActivity(new Intent(FilePicker.this,MenuActivity.class));
			overridePendingTransition(0, 0);
	    }

	}
    
    private class AllAction implements Action {
	    @Override
	    public int getDrawable() {
	        return R.drawable.ic_selection_off;
	    }

	    @Override
	    public void performAction(View view) {	    	
	    	uploadFiles.clear();
	    	uploadNames.clear();
	    	List<File> files = mAdapter.getFiles();
	    	if(files!=null && files.size()>0){
	    		for(File file : files){
	    			String name = file.getName();
            		int sp = name.lastIndexOf(".");
	    			if(file.isFile() && sp>=0 && Constant.supportFileType.contains(name.substring(sp+1,name.length()))){
	    				uploadFiles.put(file.getName(), file.getAbsolutePath());
	    				uploadNames.put(file.getName(), file.getAbsolutePath());
	    			}
	    		}
	    		
	    		actionBar.removeAllActions();
	    		actionBar.addAction(new NoneAction());
	    		actionBar.addAction(new UploadAction());
	    		actionBar.addAction(new InfoAction());
	    		mAdapter.notifyDataSetChanged();
	    		//handler.sendEmptyMessage(0);
	    		
	    	}
	    }

	}
    
    private class InfoAction implements Action {
	    @Override
	    public int getDrawable() {
	        return R.drawable.ic_help;
	    }

	    @Override
	    public void performAction(View view) {	
	    	LayoutInflater inflater 	= (LayoutInflater) FilePicker.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final Dialog dialog = new Dialog(FilePicker.this);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			View container	= (View) inflater.inflate(R.layout.file_supported_detail, null);
			dialog.setContentView(container);
			dialog.show();
	    }

	}
    
    private class NoneAction implements Action {
	    @Override
	    public int getDrawable() {
	        return R.drawable.ic_selection_on;
	    }

	    @Override
	    public void performAction(View view) {	    	
	    	uploadFiles.clear();
	    	uploadNames.clear();
	    	actionBar.removeAllActions();
    		actionBar.addAction(new AllAction());
    		actionBar.addAction(new InfoAction());
    		mAdapter.notifyDataSetChanged();
	    	//handler.sendEmptyMessage(0);
	    }

	}

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && !mPrevFolders.isEmpty()) {
            File folder = mPrevFolders.pop();
            loadFolder(folder);
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        initActionBar();
        File root = Environment.getExternalStorageDirectory();
        ROOT_NAME = root.getAbsolutePath();
        loadFolder(root);
    }
    
    private void initActionBar(){
		actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setHomeAction(new HomeAction());
		actionBar.addAction(new AllAction());
		actionBar.addAction(new InfoAction());
		actionBar.setTitle(this.getString(R.string.title_upload_file));
    }
    
    private class UploadAction implements Action {
	    @Override
	    public int getDrawable() {
	        return R.drawable.ic_tick;
	    }

	    @Override
	    public void performAction(View view) {
	    	int size = uploadFiles.size();
	    	String[] names = new String[size];
	    	String[] files = new String[size];
	    	int i = 0;
	    	if(!uploadFiles.isEmpty()){
	    		Iterator<String> ite = uploadFiles.keySet().iterator();
	    		while(ite.hasNext()){
	    			String key = ite.next();
	    			names[i] = uploadNames.get(key);
	    			files[i] = uploadFiles.get(key);
	    			i++;
	    		}
	    	}
		    	
	        Intent data = new Intent();
	        data.putExtra("names", names);
	        data.putExtra("files", files);
	        setResult(FileListActivity.RLT_FILE_PICK, data);
	        finish();	    	
	    }

	}

    private void loadFolder(final File folder) {
        assert folder.isDirectory();
        setTitle(folder.getName());
        
      //initial 'Up To' item
		if(folder.getAbsolutePath().equals(ROOT_NAME)){
			upLst.setVisibility(View.GONE);
		}else{
			TextView upText = (TextView) this.findViewById(R.id.fl_up_txt);
			upText.setText(this.getString(R.string.lab_up_to) +" "+ folder.getParent());
			upLst.setVisibility(View.VISIBLE);
			upLst.setOnClickListener(new View.OnClickListener() {			
				@Override
				public void onClick(View v) {
					loadFolder(folder.getParentFile());
				}
			});
		}
        

        mCurrentFolder = folder;
        uploadFiles.clear();
        uploadNames.clear();
        
        ProgressDialog progressDialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
        ArrayList<File> adapterFiles = mAdapter.getFiles();
        adapterFiles.clear();
        try{
        	for(File file : folder.listFiles()){
            	if(file.isDirectory()){
            		adapterFiles.add(file);
            	}else{
            		String name = file.getName();
            		int sp = name.lastIndexOf(".");
            		if(sp>=0 && Constant.supportFileType.contains(name.substring(sp+1,name.length()))){
            			adapterFiles.add(file);
            		}     		
            	}
            }
        }catch(Exception e){
        	e.printStackTrace();
        }
        
        if(adapterFiles.size()==0){
        	this.findViewById(R.id.pf_empty_lst).setVisibility(View.VISIBLE);
        	this.getListView().setVisibility(View.GONE);        	
        }else{
        	this.findViewById(R.id.pf_empty_lst).setVisibility(View.GONE);
        	this.getListView().setVisibility(View.VISIBLE);      
        }
        
        actionBar.removeAllActions();
        for(File file : mAdapter.getFiles()){
        	if(file.isFile()){
        		actionBar.addAction(new AllAction());
        		break;
        	}
        }
		actionBar.addAction(new InfoAction());
		
        mAdapter.notifyDataSetChanged();
        progressDialog.dismiss();
    }
}
